/*
 * @Author: xiaosihan
 * @Date: 2024-06-06 16:58:11
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-08-25 17:21:51
 */

import * as fabric from "fabric";
import utils from "@utils";
import {
  BufferGeometry,
  Camera,
  CanvasTexture,
  Group,
  Material,
  NormalBufferAttributes,
  Object3DEventMap,
  Scene,
  Sprite,
  SRGBColorSpace,
  Vector3,
  WebGLRenderer,
} from "three";
import iconPNG from "./icon.png";
import head_portraitJPG from "./head_portrait.jpg";

// 头像标签
export default class HeadPortraitLable extends Sprite {
  constructor(text: string = "0", color: string = "#ffff00") {
    super();
    this.color = color;
    this.text = text;
    this.material.map = this.texture;
    this.material.alphaTest = 0.1;
    this.material.sizeAttenuation = false;
    this.scale.set(0.05, 0.05, 0.05);
  }

  originPosition = new Vector3();

  // 这个标识在第几个mesh上面
  meshIndex = 0;

  img = new Image();

  // 绘制纹理
  canvas = (() => {
    const canvas = document.createElement("canvas");
    canvas.width = 1024;
    canvas.height = 1024;
    return canvas;
  })();

  //上下文
  ctx = this.canvas.getContext("2d")!;

  //canvas纹理
  texture = (() => {
    const texture = new CanvasTexture(this.canvas);
    texture.colorSpace = SRGBColorSpace;
    return texture;
  })();

  // 圆环图标
  static icon = (() => {
    const greenIcon = new Image();
    greenIcon.src = iconPNG;
    return greenIcon;
  })();

  color: string = "#ffffff";
  text: string = "0";
  active: boolean = true;

  //应用在canvas纹理上的参数
  _cureentConf = {
    color: "",
    text: "0",
    active: true,
  };

  //圆形背景
  fabricCircle = new fabric.Circle({
    radius: 400,
    left: 512,
    top: 512,
    originX: "center",
    originY: "center",
    fill: "#cccccc",
    stroke: "#000000",
    strokeWidth: 90,
  });

  // 文字对象
  fabricText = new fabric.IText(this._cureentConf.text, {
    width: 1024,
    height: 1024,
    left: 512,
    top: 512,
    originX: "center",
    originY: "center",
    fill: "#ffffff",
    fontSize: 600,
  });

  // 设置
  async _set({ text, color, active }: typeof this._cureentConf) {
    Object.assign(this._cureentConf, { text, color, active });

    this.ctx.clearRect(0, 0, 1024, 1024);
    this.fabricCircle.fill = color;
    this.fabricCircle.strokeWidth = this.active ? 90 : 0;
    this.fabricCircle.render(this.ctx);
    this.fabricText.set({ text: this._cureentConf.text });
    this.fabricText.render(this.ctx);

    this.texture.needsUpdate = true;
    this.material.needsUpdate = true;
  }

  onBeforeRender(
    renderer: WebGLRenderer,
    scene: Scene,
    camera: Camera,
    geometry: BufferGeometry<NormalBufferAttributes>,
    material: Material,
    group: Group<Object3DEventMap>
  ): void {
    if (
      !utils.isEqualWidth(this, this._cureentConf, ["text", "color", "active"])
    ) {
      this._set({ text: this.text, color: this.color, active: this.active });
    }
  }
}
